setwd("/home/jc227089/SRE/KB/Adap/wrapped/data/")

fname<-"Kbyl"
flist<-list.files(pattern=fname)
flist<-flist[!grepl(pattern="concat", flist)]

concat<-c()
poplist<-vector(mode="list", length=3*length(flist))
for (ii in 1:length(flist)) {
	load(flist[ii])
	for (jj in 1:length(out)){
		if (is.null(out[[jj]]$pop)) next
		xmin<--min(out[[jj]]$pop[,"X"])
		xmax<-max(out[[jj]]$pop[,"X"])
		pars<-unlist(out[[jj]]$parameters)
		Dbar<-mean(out[[jj]]$pop[,"DP"])
		Hbar<-mean(out[[jj]]$pop[,"HP"])
		concat<-rbind(concat, c(pars, lim=0.5*(xmin+xmax), Dbar=Dbar, Hbar=Hbar))
		poplist[[(ii-1)*length(out)+jj]]<-out[[jj]]$pop
	}
}
save(concat, poplist, file="concat_Kbylambda_wrapped.Rdata")

zmat<-tapply(concat[,"Dbar"], list(K=concat[,"K"], Lambda=concat[,"lambda"]), mean)
zmat[is.na(zmat)]<-0
pdf(file="../figures/KbyL_Dbar.pdf")
	contour(x=as.numeric(levels(as.factor(concat[,"K"]))), y=as.numeric(levels(as.factor(concat[,"lambda"]))), z=zmat, xlab="K", ylab="Lambda")
	plot(x=as.numeric(colnames(zmat)), apply(zmat, 2, mean), xlab="lambda", ylab="Dispersal")
	plot(x=as.numeric(row.names(zmat)), apply(zmat, 1, mean), xlab="K", ylab="Dispersal")
dev.off()



zmat<-tapply(concat[,"Hbar"], list(K=concat[,"K"], Lambda=concat[,"lambda"]), mean)
zmat[is.na(zmat)]<-0
pdf(file="../figures/KbyL_Hbar.pdf")
	contour(x=as.numeric(levels(as.factor(concat[,"K"]))), y=as.numeric(levels(as.factor(concat[,"lambda"]))), z=zmat, xlab="K", ylab="Lambda")
	plot(x=as.numeric(colnames(zmat)), apply(zmat, 2, mean), xlab="lambda", ylab="Habitat")
	plot(x=as.numeric(row.names(zmat)), apply(zmat, 1, mean), xlab="K", ylab="Habitat")
dev.off()